﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Dragon.Library.Framework.Exception;
using Dragon.Library.Utility.Config;
using NHibernate;
using NHibernate.Cfg;

namespace Dragon.Library.Utility.NHibernate
{
    public static class SessionFactory
    {
        private static readonly Dictionary<string, ISessionFactory> HnSessionFactoryDictionary;
        //[ThreadStatic]
        private static readonly Dictionary<string, ISession> SessionDictionary;

        static SessionFactory()
        {
            SessionDictionary = new Dictionary<string, ISession>();
            HnSessionFactoryDictionary = new Dictionary<string, ISessionFactory>();

            var cfg = new Configuration();
            cfg.Configure();
            string configValue = ConfigUtility.GetAppSettingsValue("NHibernateAssembly");
            if (configValue == null || string.IsNullOrEmpty(configValue.Trim()))
                throw new NullReferenceException("NHibernateAssembly配置为空！");
            cfg.AddAssembly(Assembly.Load(configValue));
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
            HnSessionFactoryDictionary.Add("", sessionFactory);
        }

        public static void InitConfig(string configFileName)
        {
            if (HnSessionFactoryDictionary.ContainsKey(configFileName))
                return;
            var cfg = new Configuration();
            cfg.Configure(configFileName);
            string configValue = ConfigUtility.GetAppSettingsValue("NHibernateAssembly");
            if (configValue == null || string.IsNullOrEmpty(configValue.Trim()))
                throw new NullReferenceException("NHibernateAssembly配置为空！");
            cfg.AddAssembly(Assembly.Load(configValue));
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
            HnSessionFactoryDictionary.Add(configFileName, sessionFactory);
        }

        /// <summary>
        /// 获取session
        /// </summary>
        /// <param name="sessionKey">session键值</param>
        /// <returns></returns>
        //public static ISession GetSession(string sessionKey)
        //{
        //    if (HnSessionFactoryDictionary.ContainsKey("") == false)
        //        throw new SessionFactoryIsClosedException();
        //    ISession currentSession;
        //    if (!SessionDictionary.ContainsKey(sessionKey))
        //    {
        //        currentSession = HnSessionFactoryDictionary[""].OpenSession();
        //        SessionDictionary.Add(sessionKey, currentSession);
        //    }
        //    else
        //    {
        //        currentSession = SessionDictionary[sessionKey];
        //    }
        //    return currentSession;
        //}

        public static ISession GetSession(string sessionKey, string configFileName)
        {
            if (HnSessionFactoryDictionary.ContainsKey(configFileName) == false)
                throw new SessionFactoryIsClosedException();
            ISession currentSession;
            if (!SessionDictionary.ContainsKey(sessionKey))
            {
                currentSession = HnSessionFactoryDictionary[configFileName].OpenSession();
                SessionDictionary.Add(sessionKey, currentSession);
            }
            else
            {
                currentSession = SessionDictionary[sessionKey];
            }
            return currentSession;
        }

        /// <summary>
        /// 关闭session
        /// </summary>
        /// <param name="sessionKey">session键值</param>
        public static void CloseSession(string sessionKey)
        {
            if (SessionDictionary.Count == 0) return;
            if (SessionDictionary.ContainsKey(sessionKey))
            {
                try
                {
                    SessionDictionary[sessionKey].Clear();
                    if (SessionDictionary[sessionKey].IsOpen)
                        SessionDictionary[sessionKey].Close();
                }
                catch (Exception)
                {
                }
                finally
                {
                    SessionDictionary[sessionKey].Dispose();
                }


                SessionDictionary.Remove(sessionKey);
            }
            //ISession currentSession = Dictionary[sessionKey];
            //if (currentSession == null)
            //{
            //    return;
            //}


            //currentSession.Clear();
            //Dictionary.Remove(sessionKey);
        }

        /// <summary>
        /// 关闭SessionFactory
        /// </summary>
        public static void CloseSessionFactory(string configFileName)
        {
            if (HnSessionFactoryDictionary.ContainsKey(configFileName))
            {
                if (!HnSessionFactoryDictionary[configFileName].IsClosed) HnSessionFactoryDictionary[configFileName].Close();
                HnSessionFactoryDictionary[configFileName].Dispose();

            }
        }
    }
}
